package ce.com.cenewbluesdk.uitl;

import android.annotation.TargetApi;
import android.bluetooth.BluetoothDevice;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Build;
import android.util.Log;


@TargetApi(Build.VERSION_CODES.KITKAT)
public abstract class BtBondReceiver extends BaseBroadcastReceiver {
    @Override
    public void onReceive(Context context, Intent intent) {
        String action = intent.getAction();
        if (BluetoothDevice.ACTION_PAIRING_REQUEST.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            int pairingVariant = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_VARIANT, -1);
            int paringKey = intent.getIntExtra(BluetoothDevice.EXTRA_PAIRING_KEY, -1);
            if (device == null) {
                return;
            }
            onPairingRequest(device, pairingVariant, paringKey);

            Log.e("liu", "弹出匹配框  devMac:" + device.getAddress() +
                    "   pairingVariant=" + pairingVariant +
                    "   paringKey=" + paringKey);

        } else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
            BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
            if (device == null) {
                return;
            }
            int pervState = intent.getIntExtra(BluetoothDevice.EXTRA_PREVIOUS_BOND_STATE, -1);
            int state = intent.getIntExtra(BluetoothDevice.EXTRA_BOND_STATE, -1);

            Log.e("liu", "匹配状态改变  devMac:" + device.getAddress() +
                    "   pervState=" + pervState +
                    "   state=" + state);
            if (pervState == BluetoothDevice.BOND_BONDING && state == BluetoothDevice.BOND_BONDED) {
                onBounded(device);
            } else if (pervState == BluetoothDevice.BOND_BONDED && state == BluetoothDevice.BOND_NONE) {
                onUnbonded(device);
            }
        }
    }

    protected void onUnbonded(BluetoothDevice device) {
    }

    protected void onBounded(BluetoothDevice device) {
    }

    protected abstract void onPairingRequest(BluetoothDevice device, int pairingVariant, int paringKey);

    @Override
    public IntentFilter createIntentFilter() {
        IntentFilter filter = new IntentFilter();
        filter.addAction(BluetoothDevice.ACTION_PAIRING_REQUEST);
        filter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        return filter;
    }
}
